package me.xiaosiqi.syt.cmn.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import me.xiaosiqi.syt.cmn.listener.DictImportListener;
import me.xiaosiqi.syt.cmn.mapper.DictMapper;
import me.xiaosiqi.syt.cmn.service.DictService;
import me.xiaosiqi.syt.model.cmn.Dict;
import me.xiaosiqi.syt.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaosiqi
 * @date 2022/1/25 23:00
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId, id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        for (Dict dict : dicts) {
            dict.setHasChildren(isChildren(dict.getId()));
        }
        return dicts;
    }

    @SneakyThrows
    @Override
    public void exportData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("数据字典", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(list());
    }

    @SneakyThrows
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importData(MultipartFile file) {
        EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictImportListener(this)).sheet().doRead();
    }

    @Override
    public void saveDictEeVo(DictEeVo dictEeVo) {
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictEeVo, dict);
        this.saveOrUpdate(dict);
    }

    /**
     * 判断id下是否有子节点
     *
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId, id);
        Integer integer = baseMapper.selectCount(wrapper);
        return integer > 0;
    }
}
